package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WECHAR_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public  UserLoginVO login(UserLoginDTO userLoginDTO) throws IOException {
        //1.调用微信服务接口，获取当前用户openid
        //1.1设置请求参数
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("appid",weChatProperties.getAppid());
        hashMap.put("secret",weChatProperties.getSecret());
        hashMap.put("js_code",userLoginDTO.getCode());
        hashMap.put("grant_type","authorization_code");
        //1.2传入请求地址和参数，指定请求方式为get请求，并得到响应体JSON字符串
        String s = HttpClientUtil.doGet(WECHAR_LOGIN, hashMap);
        //1.3将json字符串转化为json对象
        JSONObject jsonObject = JSON.parseObject(s);
        Object openid = jsonObject.get("openid");
        //2.判断openid是否为空，为空则登录失败
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.判断用户是否为新用户
        User user= userMapper.findByOpenid(openid.toString());
        //4.是新用户，注册用户
        User newUser = null;
        if(user==null){
            newUser=new User();
            newUser.setOpenid(openid.toString());
            newUser.setCreateTime(LocalDateTime.now());
            userMapper.add(newUser);
        } else {
            newUser=user;
        }
        //5.返回UserLoginVO
        //5.1创建UserLoginVO对象，并对openid和id进行赋值
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(openid.toString());
        userLoginVO.setId(newUser.getId());
        Map<String,Object> map=new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID,newUser.getId());
        //5.2为用户创建微信登录令牌
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        //String token = JwtTokenUtils.createToken(openid.toString());
        userLoginVO.setToken(jwt);
        return userLoginVO;
    }


}
